package com.testspring.util;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

public class JSONUtil {
	private static final Log log = LogFactory.getLog(JSONUtil.class);
	public static ObjectMapper mapper = new ObjectMapper();
	private static JSONUtil jsonUtil = null;

	private JSONUtil() {
	}

	public static JSONUtil getInstance() {
		if (jsonUtil == null)
			jsonUtil = new JSONUtil();
		return jsonUtil;
	}

	public String fromObject(Object obj) throws Exception {
		StringWriter stringWriter = new StringWriter();
		mapper.writeValue(stringWriter, obj);
		return stringWriter.toString();
	}

	public List<?> toList(String json) throws Exception {
		log.debug("Get json string is:" + json);
		return mapper.readValue(json, List.class);
	}

	public Map<?, ?> toMap(String json) throws Exception {
		return mapper.readValue(json, Map.class);
	}
}
